<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java,多线程," />










<meta name="description" content="一、如下方式存在的问题123456new Thread() &amp;#123;    @Override    public void run() &amp;#123;        &#x2F;&#x2F; 业务逻辑    &amp;#125;&amp;#125;.start();  首先频繁的创建、销毁对象是一个很消耗性能的事情； 如果用户量比较大，导致占用过多的资源，可能会导致我们的服务由于资源不足而宕机； 综上所述，在实际的开发中，这种操">
<meta name="keywords" content="Java,多线程">
<meta property="og:type" content="article">
<meta property="og:title" content="Java多线程的四种用法与使用场景">
<meta property="og:url" content="http:&#x2F;&#x2F;yoursite.com&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;index.html">
<meta property="og:site_name" content="一个程序员的成长">
<meta property="og:description" content="一、如下方式存在的问题123456new Thread() &amp;#123;    @Override    public void run() &amp;#123;        &#x2F;&#x2F; 业务逻辑    &amp;#125;&amp;#125;.start();  首先频繁的创建、销毁对象是一个很消耗性能的事情； 如果用户量比较大，导致占用过多的资源，可能会导致我们的服务由于资源不足而宕机； 综上所述，在实际的开发中，这种操">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;blog&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;1.png">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;blog&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;2.gif">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;blog&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;3.gif">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;blog&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;4.gif">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;blog&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;5.gif">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;blog&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;6.gif">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;blog&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;7.gif">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;blog&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;8.gif">
<meta property="og:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;blog&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;9.gif">
<meta property="og:updated_time" content="2019-10-30T08:31:25.404Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http:&#x2F;&#x2F;yoursite.com&#x2F;blog&#x2F;2019&#x2F;10&#x2F;30&#x2F;Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF&#x2F;1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/10/30/Java线程池的四种用法与使用场景/"/>





  <title>Java多线程的四种用法与使用场景 | 一个程序员的成长</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">一个程序员的成长</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">生活不止眼前的苟且</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/2019/10/30/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="小涛">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head_img.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一个程序员的成长">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java多线程的四种用法与使用场景</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-10-30T09:22:00+08:00">
                2019-10-30
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" itemprop="url" rel="index">
                    <span itemprop="name">多线程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="一、如下方式存在的问题"><a href="#一、如下方式存在的问题" class="headerlink" title="一、如下方式存在的问题"></a>一、如下方式存在的问题</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">new Thread() &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        // 业务逻辑</span><br><span class="line">    &#125;</span><br><span class="line">&#125;.start();</span><br></pre></td></tr></table></figure>
<ul>
<li>首先频繁的创建、销毁对象是一个很消耗性能的事情；</li>
<li>如果用户量比较大，导致占用过多的资源，可能会导致我们的服务由于资源不足而宕机；</li>
<li>综上所述，在实际的开发中，这种操作其实是不可取的一种方式。</li>
</ul>
<h3 id="二、使用线程池有什么优点"><a href="#二、使用线程池有什么优点" class="headerlink" title="二、使用线程池有什么优点"></a>二、使用线程池有什么优点</h3><ul>
<li>线程池中线程的使用率提升，减少对象的创建、销毁；</li>
<li>线程池可以控制线程数，有效的提升服务器的使用资源，避免由于资源不足而发生宕机等问题；</li>
</ul>
<h3 id="三、线程池的四种使用方式"><a href="#三、线程池的四种使用方式" class="headerlink" title="三、线程池的四种使用方式"></a>三、线程池的四种使用方式</h3><h4 id="1、newCachedThreadPool"><a href="#1、newCachedThreadPool" class="headerlink" title="1、newCachedThreadPool"></a>1、newCachedThreadPool</h4><ul>
<li>创建一个线程池，如果线程池中的线程数量过大，它可以有效的回收多余的线程，如果线程数不足，那么它可以创建新的线程。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">public static void method() throws Exception &#123;</span><br><span class="line"></span><br><span class="line">    ExecutorService executor = Executors.newCachedThreadPool();</span><br><span class="line"></span><br><span class="line">    for (int i = 0; i &lt; 5; i++) &#123;</span><br><span class="line"></span><br><span class="line">        final int index = i;</span><br><span class="line"></span><br><span class="line">        Thread.sleep(1000);</span><br><span class="line"></span><br><span class="line">        executor.execute(new Runnable() &#123;</span><br><span class="line">            @Override</span><br><span class="line">            public void run() &#123;</span><br><span class="line">                System.out.println(Thread.currentThread().getName() + &quot;  &quot; + index);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果</p>
<p><img src="/blog/2019/10/30/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/1.png" alt="image"></p>
<p>通过分析我看可以看到，至始至终都由一个线程执行，实现了线程的复用，并没有创建多余的线程。</p>
<p>如果当我们的业务需要一定的时间进行处理，那么将会出现什么结果。我们来模拟一下。</p>
<p><img src="/blog/2019/10/30/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/2.gif" alt="image"></p>
<p>可以明显的看出，现在就需要几条线程来交替执行。</p>
<ul>
<li><strong>不足</strong>：这种方式虽然可以根据业务场景自动的扩展线程数来处理我们的业务，但是最多需要多少个线程同时处理缺是我们无法控制的；</li>
<li><strong>优点</strong>：如果当第二个任务开始，第一个任务已经执行结束，那么第二个任务会复用第一个任务创建的线程，并不会重新创建新的线程，提高了线程的复用率；</li>
</ul>
<h4 id="2、newFixedThreadPool"><a href="#2、newFixedThreadPool" class="headerlink" title="2、newFixedThreadPool"></a>2、newFixedThreadPool</h4><p>这种方式可以指定线程池中的线程数。举个栗子，如果一间澡堂子最大只能容纳20个人同时洗澡，那么后面来的人只能在外面排队等待。如果硬往里冲，那么只会出现一种情景，摩擦摩擦…</p>
<p>首先测试一下最大容量为一个线程，那么会不会是我们预测的结果。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">public static void method_01() throws InterruptedException &#123;</span><br><span class="line"></span><br><span class="line">    ExecutorService executor = Executors.newFixedThreadPool(1);</span><br><span class="line"></span><br><span class="line">    for (int i = 0; i &lt; 10; i++) &#123;</span><br><span class="line"></span><br><span class="line">        Thread.sleep(1000);</span><br><span class="line">        final int index = i;</span><br><span class="line"></span><br><span class="line">        executor.execute(() -&gt; &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">                Thread.sleep(2 * 1000);</span><br><span class="line">            &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + &quot;  &quot; + index);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    executor.shutdown();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行结果</p>
<p><img src="/blog/2019/10/30/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/3.gif" alt="image"></p>
<p>我们改为3条线程再来看下结果</p>
<p><img src="/blog/2019/10/30/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/4.gif" alt="image"></p>
<p><strong>优点</strong>：两个结果综合说明，newFixedThreadPool的线程数是可以进行控制的，因此我们可以通过控制最大线程来使我们的服务器打到最大的使用率，同事又可以保证及时流量突然增大也不会占用服务器过多的资源。</p>
<h4 id="3、newScheduledThreadPool"><a href="#3、newScheduledThreadPool" class="headerlink" title="3、newScheduledThreadPool"></a>3、newScheduledThreadPool</h4><p>该线程池支持定时，以及周期性的任务执行，我们可以延迟任务的执行时间，也可以设置一个周期性的时间让任务重复执行。<br>该线程池中有以下两种延迟的方法。</p>
<ul>
<li><strong>scheduleAtFixedRate</strong></li>
</ul>
<p>测试一</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public static void method_02() &#123;</span><br><span class="line">    ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);</span><br><span class="line"></span><br><span class="line">    executor.scheduleAtFixedRate(new Runnable() &#123;</span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            long start = new Date().getTime();</span><br><span class="line">            System.out.println(&quot;scheduleAtFixedRate 开始执行时间:&quot; +</span><br><span class="line">                    DateFormat.getTimeInstance().format(new Date()));</span><br><span class="line">            try &#123;</span><br><span class="line">                Thread.sleep(5000);</span><br><span class="line">            &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            long end = new Date().getTime();</span><br><span class="line">            System.out.println(&quot;scheduleAtFixedRate 执行花费时间=&quot; + (end - start) / 1000 + &quot;m&quot;);</span><br><span class="line">            System.out.println(&quot;scheduleAtFixedRate 执行完成时间：&quot; + DateFormat.getTimeInstance().format(new Date()));</span><br><span class="line">            System.out.println(&quot;======================================&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, 1, 5, TimeUnit.SECONDS);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果</p>
<p><img src="/blog/2019/10/30/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/5.gif" alt="image"></p>
<p>测试二</p>
<p><img src="/blog/2019/10/30/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/6.gif" alt="image"></p>
<p><strong>总结</strong>：以上两种方式不同的地方是任务的执行时间，如果间隔时间大于任务的执行时间，任务不受执行时间的影响。如果间隔时间小于任务的执行时间，那么任务执行结束之后，会立马执行，至此间隔时间就会被打乱。</p>
<ul>
<li>scheduleWithFixedDelay</li>
</ul>
<p>测试一</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">public static void method_03() &#123;</span><br><span class="line">    ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);</span><br><span class="line"></span><br><span class="line">    executor.scheduleWithFixedDelay(new Runnable() &#123;</span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            long start = new Date().getTime();</span><br><span class="line">            System.out.println(&quot;scheduleWithFixedDelay 开始执行时间:&quot; +</span><br><span class="line">                    DateFormat.getTimeInstance().format(new Date()));</span><br><span class="line">            try &#123;</span><br><span class="line">                Thread.sleep(1000);</span><br><span class="line">            &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            long end = new Date().getTime();</span><br><span class="line">            System.out.println(&quot;scheduleWithFixedDelay执行花费时间=&quot; + (end - start) / 1000 + &quot;m&quot;);</span><br><span class="line">            System.out.println(&quot;scheduleWithFixedDelay执行完成时间：&quot;</span><br><span class="line">                    + DateFormat.getTimeInstance().format(new Date()));</span><br><span class="line">            System.out.println(&quot;======================================&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, 1, 2, TimeUnit.SECONDS);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果</p>
<p><img src="/blog/2019/10/30/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/7.gif" alt="image"></p>
<p>测试二</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">public static void method_03() &#123;</span><br><span class="line">    ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);</span><br><span class="line"></span><br><span class="line">    executor.scheduleWithFixedDelay(new Runnable() &#123;</span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            long start = new Date().getTime();</span><br><span class="line">            System.out.println(&quot;scheduleWithFixedDelay 开始执行时间:&quot; +</span><br><span class="line">                    DateFormat.getTimeInstance().format(new Date()));</span><br><span class="line">            try &#123;</span><br><span class="line">                Thread.sleep(5000);</span><br><span class="line">            &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            long end = new Date().getTime();</span><br><span class="line">            System.out.println(&quot;scheduleWithFixedDelay执行花费时间=&quot; + (end - start) / 1000 + &quot;m&quot;);</span><br><span class="line">            System.out.println(&quot;scheduleWithFixedDelay执行完成时间：&quot;</span><br><span class="line">                    + DateFormat.getTimeInstance().format(new Date()));</span><br><span class="line">            System.out.println(&quot;======================================&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, 1, 2, TimeUnit.SECONDS);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果</p>
<p><img src="/blog/2019/10/30/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/8.gif" alt="image"></p>
<p><strong>总结</strong>：同样的，跟scheduleWithFixedDelay测试方法一样，可以测出scheduleWithFixedDelay的间隔时间不会受任务执行时间长短的影响。</p>
<h4 id="4、newSingleThreadExecutor"><a href="#4、newSingleThreadExecutor" class="headerlink" title="4、newSingleThreadExecutor"></a>4、newSingleThreadExecutor</h4><p>这是一个单线程池，至始至终都由一个线程来执行。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">public static void method_04() &#123;</span><br><span class="line"></span><br><span class="line">    ExecutorService executor = Executors.newSingleThreadExecutor();</span><br><span class="line"></span><br><span class="line">    for (int i = 0; i &lt; 5; i++) &#123;</span><br><span class="line">        final int index = i;</span><br><span class="line">        executor.execute(() -&gt; &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">                Thread.sleep(2 * 1000);</span><br><span class="line">            &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(Thread.currentThread().getName() + &quot;   &quot; + index);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    executor.shutdown();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行结果<br><img src="/blog/2019/10/30/Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E7%9A%84%E5%9B%9B%E7%A7%8D%E7%94%A8%E6%B3%95%E4%B8%8E%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/9.gif" alt="image"></p>
<h3 id="四、线程池的作用"><a href="#四、线程池的作用" class="headerlink" title="四、线程池的作用"></a>四、线程池的作用</h3><p><strong>线程池的作用主要是为了提升系统的性能以及使用率</strong>。文章刚开始就提到，如果我们使用最简单的方式创建线程，如果用户量比较大，那么就会产生很多创建和销毁线程的动作，这会导致服务器在创建和销毁线程上消耗的性能可能要比处理实际业务花费的时间和性能更多。线程池就是为了解决这种这种问题而出现的。</p>
<p>同样思想的设计还有很多，比如<strong>数据库连接池</strong>，由于频繁的连接数据库，然而创建连接是一个很消耗性能的事情，所有数据库连接池就出现了。</p>

      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="https://ss.csdn.net/p?https://mmbiz.qpic.cn/mmbiz_jpg/rEQDLleOGw0oFpL1ia2Zy1ia1EiczlYXeXCMrsn9fhEicTYgd6NfssqOMxWs0JXhyychzV37TPictLf4YicsBxeFUaIw/640?" alt="小涛 wechat" style="width: 200px; max-width: 100%;"/>
    <div>更多精彩内容请关注微信公众号！</div>
</div>

      </div>
    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Java/" rel="tag"># Java</a>
          
            <a href="/blog/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag"># 多线程</a>
          
        </div>
      

      
      
      

      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/head_img.jpg"
                alt="小涛" />
            
              <p class="site-author-name" itemprop="name">小涛</p>
              <p class="site-description motion-element" itemprop="description">代码那玩意写起来它不香嘛！</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/javayuan/activities" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-zhihu"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/weixin_37158722" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-zhihu"></i>CSDN</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.liabio.cn/" title="小碗汤" target="_blank">小碗汤</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、如下方式存在的问题"><span class="nav-number">1.</span> <span class="nav-text">一、如下方式存在的问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、使用线程池有什么优点"><span class="nav-number">2.</span> <span class="nav-text">二、使用线程池有什么优点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三、线程池的四种使用方式"><span class="nav-number">3.</span> <span class="nav-text">三、线程池的四种使用方式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1、newCachedThreadPool"><span class="nav-number">3.1.</span> <span class="nav-text">1、newCachedThreadPool</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2、newFixedThreadPool"><span class="nav-number">3.2.</span> <span class="nav-text">2、newFixedThreadPool</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3、newScheduledThreadPool"><span class="nav-number">3.3.</span> <span class="nav-text">3、newScheduledThreadPool</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4、newSingleThreadExecutor"><span class="nav-number">3.4.</span> <span class="nav-text">4、newSingleThreadExecutor</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#四、线程池的作用"><span class="nav-number">4.</span> <span class="nav-text">四、线程池的作用</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">小涛</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
